package filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

import com.alibaba.fastjson.JSONObject;

import util.AjaxResultDto;
import util.ValidationUtil;

public class AuthFilter extends OncePerRequestFilter{

	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		 String uri = request.getRequestURI();
		 String[] notFilter = new String[] { "/showPage.do" ,"/login.do", "/getProjectById","/pageRegister.do","/saveRegister.do"};
		 if (uri.indexOf("do") != -1) {
			// 是否过滤
            boolean doFilter = true;
            for (String s : notFilter) {
                if (uri.indexOf(s) != -1) {
                    // 如果uri中包含不过滤的uri，则不进行过滤
                    doFilter = false;
                    break;
                }
            }
            
            if(doFilter) {
            	 String token = (String) request.getSession().getAttribute("token");
            	 if(ValidationUtil.isEmpty(token)) {
            		 request.setCharacterEncoding("UTF-8");
                     response.setCharacterEncoding("UTF-8");
                     if(request.getHeader("request_type") == "ajax") {
                    	 AjaxResultDto result = new AjaxResultDto();
                    	 result.setIsError(true);
                    	 result.setErrorMsg("尚未登录，请重新登录");
                    	 result.setErrorCode("401");
                         PrintWriter writer = response.getWriter();
                         JSONObject obj = (JSONObject) JSONObject.toJSON(result);
                         writer.print(obj);
                         writer.flush();
                         writer.close(); 
                     }else{
                    	 request.getRequestDispatcher("/pageLogin.do").forward(request,response); 
                     }
            	 }else{
            		// 如果不执行过滤，则继续
                     filterChain.doFilter(request, response);
            	 }
            } else {
                // 如果不执行过滤，则继续
                filterChain.doFilter(request, response);
            }
            
		 } else {
	            // 如果uri中不包含do，则继续
	            filterChain.doFilter(request, response);
	     }
		 
		
	}


}
